package com.silence.kotlinapp.widget

import android.annotation.TargetApi
import android.content.Context
import android.os.Build
import android.support.v7.widget.Toolbar
import android.util.AttributeSet
import com.silence.kotlinapp.R
import com.silence.kotlinapp.util.Utils





/**
 *
 *  @作者:  PJ
 *  @创建时间:    2018/6/7 / 14:12
 *  @描述:  这是一个 BaseToolbar 类.
 *
 */
class BaseToolbar: Toolbar {

    private var mFitStatusBar: Boolean
    private var mStatusBarH: Int = 0
    private var mPaddingTop:Int=0

    constructor(context: Context): this(context, null)

    constructor(context: Context, attr: AttributeSet?): super(context, attr) {
        val array = context.obtainStyledAttributes(attr, R.styleable.BaseToolbar)
        mFitStatusBar = array.getBoolean(R.styleable.BaseToolbar_fit_statusbar, true)
        val defaultBg = array.getBoolean(R.styleable.BaseToolbar_default_bg, true)
        array.recycle()
        if (defaultBg) {
            setDefaultBg()
        }

        init()
    }

    private fun init() {
        setContentInsetsAbsolute(0, 0)
        setContentInsetsRelative(0, 0)
            mPaddingTop=paddingTop
        mStatusBarH = Utils.getStatusBarH(context)
    }

    private fun setDefaultBg(): BaseToolbar {
        setBackgroundResource(R.drawable.bg_toolbar_conn)
        return this
    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            if (mFitStatusBar) {
                setMeasuredDimension(measuredWidth, Utils.getActionBarSize(context) + mStatusBarH)//折段没问题
                //这个地方不能直接用paddingtop,会导致paddingtop连续相加   要在初始化时获取 设置的paddingtop  保存起来
                setPadding(paddingLeft, mPaddingTop + mStatusBarH, paddingRight, paddingBottom)//这个出问题了  咋整
            } else{
                setMeasuredDimension(measuredWidth, Utils.getActionBarSize(context))
            }
        }
    }


    fun setBackGroundAlpha(alpha: Float): BaseToolbar {
        background.alpha = (alpha * 255).toInt()
        return this
    }

    fun isFitStatusBar(): Boolean {
        return mFitStatusBar
    }

    /**
     * 适配透明状态栏
     *
     * @param fitStatusBar
     */
    @TargetApi(value = Build.VERSION_CODES.KITKAT)
    fun setFitStatusBar(fitStatusBar: Boolean) {
        this.mFitStatusBar = fitStatusBar
        requestLayout()
    }

}